<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    
    //1.生成器函数
    function* foo() {
      console.log('111');
      yield "Hello";
      console.log('222');
      yield "World";
      console.log('333');
      yield "yzhzyzh";
      console.log('444');
    }
    
    //2.iterator：迭代器
    const result = foo();
    // console.log(result);
    
    //3.使用迭代器
    //调用一次next，就会消耗一次迭代器
    //4.执行顺序--只有调用next，才会执行foo里面的代码，每次调用执行到yield
    // const res = result.next();
    // console.log(res);
    // const res2 = result.next();
    // console.log(res2);
    // const res3 = result.next();
    // console.log(res3);
    // const res4 = result.next();
    // console.log(res4);

    //5.定义一个生成器函数，一次可以生成1~10的数字
    function* generatorNumber() {
      for(var i = 1; i <= 10; i++) {
        yield i
      }
    }
    const numItem = generatorNumber()
    // console.log(numItem.next());
    // console.log(numItem.next().value);
    
    //6. generator和Promise一起使用
    function* bar() {
      const result = yield new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve("Hello Generrator")
        }, 3000)
      })
      console.log('拿到结果：', result);
    }
    
    const it = bar();
    //第一次调用是 yield promise对象
    it.next().value.then(res => {
      //第二次调用传入res 会把第一次yield的结果 赋值给上面的result
      it.next(res)
    })
  </script>
</body>
</html>